<template>
    <div class="whiteBac mt10 p15">
      <el-form ref="dataForm" :rules="rules" :model="dataForm"  label-width="140px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="dataForm.name" :maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="商品积分" prop="integral">
          <el-input v-model="dataForm.integral" :maxlength="100"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" prop="shopType">
          <div class="mt10">
            <el-radio-group v-model="dataForm.shopType">
              <el-radio label="0">实物</el-radio>
              <el-radio label="1">虚拟</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="PC&APP列表图片" prop="listPic">
          <div class="fl">
            <el-upload
              class="avatar-uploader list-img"
              :action="uploadFileAction"
              :show-file-list="false"
              accept="image/gif,image/jpeg,image/jpg,image/bmp"
              :before-upload="beforeAvatarUpload"
              :on-success="listPicSuccess">
              <img v-if="dataForm.listPic" :src="dataForm.listPic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon list-img-icon"></i>
            </el-upload>
          </div>
          <div class="fl a-tip" style="margin-top: 50px;">请上传330*140的图片</div>
          <div class="clear"></div>
        </el-form-item>
        <el-form-item label="APP详情图片" prop="appDetailsPic">
          <div class="fl">
            <el-upload
              class="avatar-uploader app-img"
              :action="uploadFileAction"
              :show-file-list="false"
              accept="image/gif,image/jpeg,image/jpg,image/bmp"
              :before-upload="beforeAvatarUpload"
              :on-success="appDetailsSuccess">
              <img v-if="dataForm.appDetailsPic" :src="dataForm.appDetailsPic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon app-img-icon"></i>
            </el-upload>
          </div>
          <div class="fl a-tip" style="margin-top: 92px;">请上传720*450的图片</div>
          <div class="clear"></div>
        </el-form-item>
        <el-form-item label="PC详情&PC订单&APP订单图片" prop="pcDetailsPic">
          <div class="fl">
            <el-upload
              class="avatar-uploader order-img"
              :action="uploadFileAction"
              :show-file-list="false"
              accept="image/gif,image/jpeg,image/jpg,image/bmp"
              :before-upload="beforeAvatarUpload"
              :on-success="pcDetailsSuccess">
              <img v-if="dataForm.pcDetailsPic" :src="dataForm.pcDetailsPic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon order-img-icon"></i>
            </el-upload>
          </div>
          <div class="fl a-tip" style="margin-top: 156px;">请上传176*176的图片</div>
          <div class="clear"></div>
        </el-form-item>
        <el-form-item label="商品详情" prop="editorContent">
          <div id="editor">
             <!--<div v-html="dataForm.editorContent"></div>-->
          </div>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="goShoppingView('dataForm')">预览</el-button>
          <el-button size="small" type="primary" :disabled="isLetDisabled" @click="onSubmitShop('dataForm')">发布</el-button>
          <router-link class="ml10" :to="{ name: 'shopping'}">
            <el-button type="info" size="small">取消</el-button>
          </router-link>

        </el-form-item>
      </el-form>
    </div>
</template>

<script>
  import service from '@/service/index'
  import { setCookie,delCookie,getCookie,validateNumber } from '@/base/utils'
  import E from "wangeditor";
  let xss = require("xss");
    export default {
        data() {
            return {
              handleType:1, //1 新增  2 编辑
              typeId:'',
              isLetDisabled:false,
              uploadFileAction:service.haiBeiServerUpload(),
              baseData:{},
              dataForm:{
                name:'',
                integral:'0',
                shopType:'0',
                listPic:'',
                appDetailsPic:'',
                pcDetailsPic:'',
                editorContent:'',
              },
              editor: null,
              viewData:{},  //存取当前表单
              currentType:'add',   //当前为编辑状态edit  新增状态为add
              rules:{
                name:[
                  { required: true, message: "请输入商品名称", trigger: "blur" },
                  { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
                ],
                integral:[
                  { required: true, message: "请输入商品积分", trigger: "blur" },
                  { validator: validateNumber, trigger: 'blur'}
                ],
                shopType:[
                  { required: true, message: "请选择商品类型", trigger: "change" }
                ],
                listPic:[
                  { required: true, message: "请上传APP和PC的商品列表的图片", trigger: "change" }
                ],
                appDetailsPic:[
                  { required: true, message: "请上传APP详情图片", trigger: "change" }
                ],
                pcDetailsPic:[
                  { required: true, message: "请上传PC详情&订单图片", trigger: "change" }
                ],
                editorContentText:[
                  { required: true, message: "请输入商品详情", trigger: "blur" },
                  //{ min: 1, max: 2048, message: "长度在 1 到 2048 个字符", trigger: "blur" }
                ],
              }
            };
        },
        mounted() {
          this.editor = new E('#editor');
          this.editor.customConfig.zIndex = 1000;
          this.editor.customConfig.onchange = html => {
            this.dataForm.editorContent = html;
          }
          this.editor.customConfig.uploadFileName = "file";
          this.editor.customConfig.uploadImgServer = service.haiBeiServerUpload();
          this.editor.customConfig.uploadImgMaxLength = 20;
          this.editor.customConfig.uploadImgHooks = {
            customInsert: function(insertImg, result, editor) {
              console.log(insertImg,'--------',result);
              var url = result.url;
              insertImg(url);
            }
          };
          this.editor.create();
          this.typeId = this.$route.query.goodsNum;
          this.initMethod();
        },
        methods: {
          initMethod(){
            if(this.typeId==='view'){
              this.baseData = getCookie('viewData')||{};
              this.assignment();
              //console.log(JSON.stringify(this.baseData),'--------');
            }else if(this.typeId==='add'){
              this.typeIdIsAdd();
            }else {
              this.typeIdIsEdit();
            }
          },
          assignment(){  //初始化赋值
            this.dataForm.name = this.baseData.name;
            this.dataForm.integral = this.baseData.integral;
            this.dataForm.shopType = this.baseData.type;
            this.dataForm.listPic = this.baseData.img_url;
            this.dataForm.appDetailsPic = this.baseData.img_url_detail_app;
            this.dataForm.pcDetailsPic = this.baseData.img_url_detail_pc;
            this.editor.txt.html(this.baseData.simple_desc);
            this.dataForm.editorContent = this.baseData.simple_desc;
          },
          typeIdIsEdit(){   //编辑时查询当前ID的详细内容并赋值到表单
            service.haiBeiServerQueryGoodsById({id:this.typeId}).then(res => {
              if (res.success) {
                this.baseData = res.result;
                this.assignment();
              }else{
                this.$message({type:'error', message:res.msg});
                return;
              }
            });
          },
          typeIdIsAdd(){  //初始化表单
            this.dataForm.name='';
            this.dataForm.integral='';
            this.dataForm.shopType='0';
            this.dataForm.listPic='';
            this.dataForm.appDetailsPic='';
            this.dataForm.pcDetailsPic='';
            this.editor.txt.html('<div></div>');
            this.dataForm.editorContent = '';
          },
          beforeAvatarUpload(file) {
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!isLt5M) {
              this.$message.error('上传图片大小不能超过5MB!');
            }
            return isLt5M;
          },
          listPicSuccess(file){
            this.dataForm.listPic = file.url;
          },
          appDetailsSuccess(file){
            this.dataForm.appDetailsPic = file.url;
          },
          pcDetailsSuccess(file){
            this.dataForm.pcDetailsPic = file.url;
          },
          onSubmitShop(formName){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                //console.log(this.baseData.currentType)
                this.isLetDisabled = true;
                if(this.typeId === 'add' || this.baseData.currentType === 'add'){
                  //新增
                  let params = {
                    name:this.dataForm.name,
                    integral:this.dataForm.integral,
                    type:this.dataForm.shopType,
                    img_url:this.dataForm.listPic,
                    img_url_detail_pc:this.dataForm.pcDetailsPic,
                    img_url_detail_app:this.dataForm.appDetailsPic,
                    simple_desc:this.dataForm.editorContent
                  }
                  //console.log(JSON.stringify(params),'------------新增---------');
                  service.haiBeiServerAddGoods(params).then(res => {
                    if (res.success) {
                      setTimeout(()=>{
                        this.isLetDisabled = false;
                      },1000);
                      this.$router.push({name:'shopping'});
                      delCookie('viewData');
                      this.$message({type:'success', message:res.msg});
                    }else{
                      this.isLetDisabled = false;
                      this.$message({type:'error', message:res.msg});
                      return;
                    }
                  });
                }else {
                  //编辑
                  let params = {
                    id:this.baseData.id,
                    name:this.dataForm.name,
                    integral:this.dataForm.integral,
                    type:this.dataForm.shopType,
                    img_url:this.dataForm.listPic,
                    img_url_detail_pc:this.dataForm.pcDetailsPic,
                    img_url_detail_app:this.dataForm.appDetailsPic,
                    simple_desc:this.dataForm.editorContent
                  }
                  //console.log(JSON.stringify(params),'---------编辑------------');
                  service.haiBeiServerUpdateGoodsInfo(params).then(res => {
                    if (res.success) {
                      setTimeout(()=>{
                        this.isLetDisabled = false;
                      },1000);
                      this.$router.push({name:'shopping'});
                      delCookie('viewData');
                      this.$message({type:'success', message:res.msg});
                    }else{
                      this.isLetDisabled = false;
                      this.$message({type:'error', message:res.msg});
                      return;
                    }
                  });
                }
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          goShoppingView(formName){
            this.$refs[formName].validate((valid) => {
              if (valid) {
                this.toView();
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          toView(){
            if(this.baseData.id===undefined){
              this.currentType = 'add';
            }else{
              this.currentType = 'edit';
            }
            this.viewData = {
              id:this.baseData.id,
              name:this.dataForm.name,
              integral:this.dataForm.integral,
              type:this.dataForm.shopType,
              img_url:this.dataForm.listPic,
              img_url_detail_pc:this.dataForm.pcDetailsPic,
              img_url_detail_app:this.dataForm.appDetailsPic,
              simple_desc:this.dataForm.editorContent,
              currentType:this.currentType
            }
            setCookie('viewData',this.viewData);
            this.$router.push({name:'shoppingView',query:{goodsSerialNumber:'view'}});
          }
        }
    };
</script>
<style scoped></style>
